//
//  PzWebCtrl.swift
//  CUYuYinFang
//
//  Created by 蓝鳍互娱 on 2024/7/2.
//  Copyright © 2024 lixinkeji. All rights reserved.
//

import Foundation
import UIKit
import WebKit
import XHToastSwift
class PzWebCtrl: UIViewController {
    var isHiddenBack:Bool = false
    var webUrl:String?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.isHidden = true;
        makeSubView()
        webView.configuration.userContentController.add(self, name: "uploadFile")
        webView.configuration.userContentController.add(self, name: "goback")
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = true;
    }
    lazy var photoNavBackBtn: UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(backBar), for: .touchUpInside)
        btn.setBackgroundImage(UIImage(named: "pzNavBlackBackIcon"), for: .normal)
        return btn
    }()
    lazy var webView: WKWebView = {
        let webView = WKWebView(frame: .zero, configuration: webviewConfiguration)
        webView.backgroundColor = self.view.backgroundColor;
        webView.scrollView.backgroundColor = self.view.backgroundColor;
        webView.scrollView.contentInsetAdjustmentBehavior = .never
        webView.addObserver(self, forKeyPath: "title", options: .new, context: nil)
        return webView
    }()
    lazy var webviewConfiguration: WKWebViewConfiguration = {
        let webviewConfiguration = WKWebViewConfiguration()
        webviewConfiguration.preferences.javaScriptCanOpenWindowsAutomatically = true
        webviewConfiguration.suppressesIncrementalRendering = true; // 是否支持记忆读取
        webviewConfiguration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
        webviewConfiguration.setValue(true, forKey: "allowUniversalAccessFromFileURLs")
        return webviewConfiguration
    }()
    func makeSubView(){
        self.view.addSubview(webView)
        webView.snp.makeConstraints { make in
            make.edges.equalTo(0.fitScale())
        }
        if !isHiddenBack {
            self.view.addSubview(photoNavBackBtn)
            photoNavBackBtn.snp.makeConstraints { make in
                make.left.equalTo(24.fitScale())
                make.top.equalTo(PzPublicConst.ScreenTopSpaceHeight + 12.fitScale())
                make.width.height.equalTo(64.fitScale())
            }
        }
        
        let requestUrl = URLRequest(url: URL(string: webUrl)!)
        webView.load(requestUrl)
    }
    @objc func backBar(){
        self.navigationController?.popViewController(animated: true)
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if(keyPath == "title"){
            self.navigationItem.title = webView.title;
        }
    }
    func checkCameraAumLimit(_ completion: @escaping (Bool) -> Void){
        let camAumAuthStatus = PHPhotoLibrary.authorizationStatus()
        if camAumAuthStatus == .authorized{
            DispatchQueue.main.async() {
                completion(true)
            }
        }else if camAumAuthStatus == .notDetermined{
            PHPhotoLibrary.requestAuthorization { status in
                if status == .authorized{
                    DispatchQueue.main.async() {
                        completion(true)
                    }
                }else{
                    let alertCtrl = UIAlertController(title: "提示", message: "相册权限已关闭，请前往设置中打开权限", preferredStyle: .alert)
                    alertCtrl.addAction(UIAlertAction(title: "好的", style: .cancel, handler: { action in
                        DispatchQueue.main.async() {
                            completion(false)
                        }
                    }))
                    alertCtrl.addAction(UIAlertAction(title: "设置", style: .default, handler: { action in
                        if let settingUrl = URL(string: UIApplication.openSettingsURLString){
                            if UIApplication.shared.canOpenURL(settingUrl) {
                                UIApplication.shared.open(settingUrl)
                            }
                        }
                    }))
                    UIApplication.shared.delegate?.window??.rootViewController?.present(alertCtrl, animated: true)
                }
            }
        }else{
            let alertCtrl = UIAlertController(title: "提示", message: "相册权限已关闭，请前往设置中打开权限", preferredStyle: .alert)
            alertCtrl.addAction(UIAlertAction(title: "好的", style: .cancel, handler: { action in
                DispatchQueue.main.async() {
                    completion(false)
                }
            }))
            alertCtrl.addAction(UIAlertAction(title: "设置", style: .default, handler: { action in
                if let settingUrl = URL(string: UIApplication.openSettingsURLString){
                    if UIApplication.shared.canOpenURL(settingUrl) {
                        UIApplication.shared.open(settingUrl)
                    }
                }
            }))
            UIApplication.shared.delegate?.window??.rootViewController?.present(alertCtrl, animated: true)
        }
    }
    func savePhotoAlbum(photoAlbumUrl:String){
        let url = URL(string: photoAlbumUrl)
        let request = NSURLRequest(url: url!)
        NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main) { response, data, connectionError in
            if (connectionError == nil){
                let image = UIImage(data: data ?? NSData() as Data)
                UIImageWriteToSavedPhotosAlbum(image ?? UIImage(), nil, nil, nil)
                XHToast.showCenterWithText("保存成功")
            }
        }
        
    }
}
extension PzWebCtrl:WKScriptMessageHandler{
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "goback" {
            self.navigationController?.popViewController(animated: true)
        }else if message.name == "uploadFile"{
            let jumpDic:NSDictionary = message.body as! NSDictionary
            let photoUrl = jumpDic["src"]
            if photoUrl != nil {
                checkCameraAumLimit { completion in
                    if completion {
                        DispatchQueue.main.async() {
                            self.savePhotoAlbum(photoAlbumUrl: photoUrl as! String)
                        }
                    }
                }
            }
        }
    }
    
    // MARK: WKNavigationDelegate methods
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("Webview did finish loading")
    }
}
